package com.zlp.springcloud.controller;

import com.netflix.appinfo.InstanceInfo;
import com.zlp.springcloud.rule.MyLb;
import com.zlp.springcloud.entity.CommonResult;
import com.zlp.springcloud.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

/**
 * @Author: zhulaiping
 * @Date: 2021/7/10 8:27
 */
@Slf4j
@RestController
public class OrderController {

    @Autowired
    public RestTemplate restTemplate;

    //public static final String USER_URl = "http://localhost:8001";
    public static final String USER_URl = "http://CLOUD-PAYMENT-SERVICE";

    @GetMapping("/consumer/user/get/{id}")
    public CommonResult<User> getUser(@PathVariable("id") Long id) {
        return restTemplate.getForObject(USER_URl + "/user/get/" + id, CommonResult.class);
    }


    @Autowired
    MyLb mylb;
    @Autowired
    DiscoveryClient discoveryClient;

    @GetMapping("/consumer/user/lb/{id}")
    public CommonResult<User> getPaymentLB(@PathVariable("id") Long id) {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        ServiceInstance instance = mylb.instances(instances);
        URI uri = instance.getUri();
        System.out.println(uri);
        return restTemplate.getForObject(uri+"/user/get/"+id,CommonResult.class);
    }
}
